.PHONY: help setup up down restart logs build clean test lint fmt migrate seed \
        backend-shell frontend-shell db-shell redis-shell health backup restore

# Variables
COMPOSE := docker-compose
COMPOSE_PROD := docker-compose -f docker-compose.prod.yml
DOCKER := docker
BACKEND := backend
FRONTEND := frontend

# Colors for output
GREEN := \033[0;32m
YELLOW := \033[0;33m
NC := \033[0m # No Color

help:
	@echo "$(GREEN)Available commands:$(NC)"
	@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "  $(YELLOW)%-20s$(NC) %s\n", $$1, $$2}'

## Development Commands

setup: ## Initialize project (copy .env files, install dependencies)
	@echo "$(GREEN)Setting up project...$(NC)"
	cp .env.example .env
	cp $(BACKEND)/.env.example $(BACKEND)/.env
	cp $(FRONTEND)/.env.example $(FRONTEND)/.env
	@echo "$(GREEN)✓ Environment files created$(NC)"
	@echo "$(YELLOW)Please update .env with your configuration$(NC)"

up: ## Start all services (development)
	@echo "$(GREEN)Starting services...$(NC)"
	$(COMPOSE) up -d
	@echo "$(GREEN)✓ Services started$(NC)"
	@make health

down: ## Stop all services
	@echo "$(GREEN)Stopping services...$(NC)"
	$(COMPOSE) down
	@echo "$(GREEN)✓ Services stopped$(NC)"

restart: ## Restart all services
	@echo "$(GREEN)Restarting services...$(NC)"
	$(COMPOSE) restart
	@echo "$(GREEN)✓ Services restarted$(NC)"

logs: ## View logs from all services
	$(COMPOSE) logs -f

logs-backend: ## View backend logs
	$(COMPOSE) logs -f $(BACKEND)

logs-frontend: ## View frontend logs
	$(COMPOSE) logs -f $(FRONTEND)

logs-worker: ## View Celery worker logs
	$(COMPOSE) logs -f celery_worker

logs-beat: ## View Celery beat logs
	$(COMPOSE) logs -f celery_beat

build: ## Build all Docker images
	@echo "$(GREEN)Building images...$(NC)"
	$(COMPOSE) build --no-cache
	@echo "$(GREEN)✓ Images built$(NC)"

rebuild: ## Rebuild without cache
	$(COMPOSE) down
	$(COMPOSE) build --no-cache
	$(COMPOSE) up -d

clean: ## Remove stopped containers and unused images
	@echo "$(GREEN)Cleaning up...$(NC)"
	$(DOCKER) container prune -f
	$(DOCKER) image prune -f
	@echo "$(GREEN)✓ Cleanup complete$(NC)"

## Database Commands

migrate: ## Run database migrations
	@echo "$(GREEN)Running migrations...$(NC)"
	$(COMPOSE) exec $(BACKEND) alembic upgrade head
	@echo "$(GREEN)✓ Migrations complete$(NC)"

migrate-create: ## Create a new migration (arg: NAME=migration_name)
	@echo "$(GREEN)Creating migration: $(NAME)$(NC)"
	$(COMPOSE) exec $(BACKEND) alembic revision --autogenerate -m "$(NAME)"

migrate-downgrade: ## Downgrade one migration
	@echo "$(GREEN)Downgrading migration...$(NC)"
	$(COMPOSE) exec $(BACKEND) alembic downgrade -1

seed: ## Seed database with sample data
	@echo "$(GREEN)Seeding database...$(NC)"
	$(COMPOSE) exec $(BACKEND) python -m app.db.seed
	@echo "$(GREEN)✓ Database seeded$(NC)"

backup: ## Backup PostgreSQL database
	@echo "$(GREEN)Backing up database...$(NC)"
	@mkdir -p backups
	@$(COMPOSE) exec -T postgres pg_dump -U videoadmin video_platform > backups/backup_$$(date +%Y%m%d_%H%M%S).sql
	@echo "$(GREEN)✓ Backup complete$(NC)"

restore: ## Restore database from backup (arg: FILE=backup_file.sql)
	@echo "$(GREEN)Restoring database from $(FILE)...$(NC)"
	@cat $(FILE) | $(COMPOSE) exec -T postgres psql -U videoadmin -d video_platform
	@echo "$(GREEN)✓ Restore complete$(NC)"

## Testing Commands

test: ## Run backend tests
	@echo "$(GREEN)Running tests...$(NC)"
	$(COMPOSE) exec $(BACKEND) pytest tests/ -v --cov=app

test-frontend: ## Run frontend tests
	@echo "$(GREEN)Running frontend tests...$(NC)"
	cd $(FRONTEND) && npm test

test-coverage: ## Generate test coverage report
	@echo "$(GREEN)Generating coverage...$(NC)"
	$(COMPOSE) exec $(BACKEND) pytest tests/ --cov=app --cov-report=html
	@echo "$(GREEN)✓ Report generated in htmlcov/index.html$(NC)"

## Code Quality Commands

lint: ## Lint Python code
	@echo "$(GREEN)Linting Python code...$(NC)"
	$(COMPOSE) exec $(BACKEND) flake8 app/ tests/
	@echo "$(GREEN)✓ Linting complete$(NC)"

fmt: ## Format code (Black + isort)
	@echo "$(GREEN)Formatting code...$(NC)"
	$(COMPOSE) exec $(BACKEND) black app/ tests/
	$(COMPOSE) exec $(BACKEND) isort app/ tests/
	@echo "$(GREEN)✓ Formatting complete$(NC)"

type-check: ## Type check Python code
	@echo "$(GREEN)Type checking...$(NC)"
	$(COMPOSE) exec $(BACKEND) mypy app/
	@echo "$(GREEN)✓ Type check complete$(NC)"

lint-frontend: ## Lint frontend code
	@echo "$(GREEN)Linting frontend...$(NC)"
	cd $(FRONTEND) && npm run lint

## Interactive Commands

backend-shell: ## Open backend container shell
	$(COMPOSE) exec $(BACKEND) /bin/bash

frontend-shell: ## Open frontend container shell
	$(COMPOSE) exec $(FRONTEND) /bin/sh

db-shell: ## Connect to PostgreSQL database
	$(COMPOSE) exec postgres psql -U videoadmin -d video_platform

redis-shell: ## Connect to Redis CLI
	$(COMPOSE) exec redis redis-cli -a redispass

## Service Health & Status

health: ## Check health of all services
	@echo "$(GREEN)Checking service health...$(NC)"
	@$(COMPOSE) ps
	@echo ""
	@echo "$(GREEN)Service URLs:$(NC)"
	@echo "  Frontend:     http://localhost:3000"
	@echo "  API:          http://localhost:8000"
	@echo "  API Docs:     http://localhost:8000/docs"
	@echo "  MinIO:        http://localhost:9001"
	@echo "  Flower:       http://localhost:5555"
	@echo "  PostgreSQL:   localhost:5432"
	@echo "  Redis:        localhost:6379"

status: ## Show service status
	@$(COMPOSE) ps

## Celery Commands

celery-purge: ## Purge all pending tasks
	@echo "$(GREEN)Purging Celery tasks...$(NC)"
	$(COMPOSE) exec celery_worker celery -A app.tasks purge
	@echo "$(GREEN)✓ Tasks purged$(NC)"

celery-inspect: ## Inspect active Celery tasks
	@echo "$(GREEN)Active tasks:$(NC)"
	$(COMPOSE) exec celery_worker celery -A app.tasks inspect active

celery-stats: ## Show Celery worker stats
	@echo "$(GREEN)Worker statistics:$(NC)"
	$(COMPOSE) exec celery_worker celery -A app.tasks inspect stats

## Production Commands

prod-up: ## Start production environment
	@echo "$(GREEN)Starting production services...$(NC)"
	$(COMPOSE_PROD) up -d
	@echo "$(GREEN)✓ Production services started$(NC)"

prod-down: ## Stop production environment
	@echo "$(GREEN)Stopping production services...$(NC)"
	$(COMPOSE_PROD) down
	@echo "$(GREEN)✓ Production services stopped$(NC)"

prod-logs: ## View production logs
	$(COMPOSE_PROD) logs -f

prod-migrate: ## Run migrations in production
	@echo "$(GREEN)Running migrations in production...$(NC)"
	$(COMPOSE_PROD) exec $(BACKEND) alembic upgrade head
	@echo "$(GREEN)✓ Migrations complete$(NC)"

## Utility Commands

install-hooks: ## Install git pre-commit hooks
	@echo "$(GREEN)Installing pre-commit hooks...$(NC)"
	cd $(BACKEND) && pre-commit install
	@echo "$(GREEN)✓ Hooks installed$(NC)"

version: ## Show application version
	@echo "Version: 1.0.0"

.DEFAULT_GOAL := help
